//
//  FMPlayerVC.m
//  NewMyMusicAPP
//
//  Created by 11_wyq on 15/6/21.
//  Copyright (c) 2015年 lanou3g.com 蓝鸥科技. All rights reserved.
//

#import "FMPlayerVC.h"
#import "FMPersonModel.h"
@interface FMPlayerVC ()

@property(nonatomic,retain)CustomLabel *customLabel;

@end

@implementation FMPlayerVC

//将播放也面设置成单例类
+(instancetype)shareHandleController
{
    //创建单例对象
    static FMPlayerVC *rootVC = nil;
    
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        
        rootVC = [[FMPlayerVC alloc] init];
        
    });
    
    return rootVC;
}



-(void)viewWillAppear:(BOOL)animated
{
   
        
    
    if(_FMPlayerV.indexPath == self.indexPath){
   
    [_FMPlayerV spinOn];//图片旋转


        }else{
        
         [self getMassage];
        FMPersonModel *model = [_Audio objectAtIndex:self.indexPath.row];
        //创建audioStreamer
            NSLog(@"model.url = %@",model.title);
        _url = [NSURL URLWithString:model.playUrl32];
        [_audioPlayer playURL:_url];//开始播放
            

        _number = self.indexPath.row ;
        _FMPlayerV.indexPath = self.indexPath;
        self.musicURL = model.playUrl32;
        [_FMPlayerV ContinueToRotate];//继续旋转
        [_FMPlayerV spinOn];//图片旋转
        [_FMPlayerV.button setBackgroundImage:[UIImage imageNamed:@"toolbar_pause_n@2x.png"] forState:UIControlStateNormal];//播放按钮图片
            _FMPlayerV.isPlaying = YES;
            _FMPlayerV.isRotating = YES;
              _myTitle.text = self.title;
            
            
            //判断是否收藏过
            [[DataHandle shareHandleController]openDB];
            NSMutableArray *array = [[DataHandle shareHandleController]selectMusicFMCollection];
            if (array.count == 0) {
                [_FMPlayerV.likeButton setBackgroundImage:[UIImage imageNamed:@"circlelist_heart@2x.png"] forState:UIControlStateNormal];
                _FMPlayerV.isCollection = NO;
            }else{
            for (FMPersonModel *player in array) {
              
                if ([player.title isEqualToString:self.title]) {
                    [_FMPlayerV.likeButton setBackgroundImage:[UIImage imageNamed:@"circlelist_heartup@2x.png"] forState:UIControlStateNormal];//收藏过变成红心
                    _FMPlayerV.isCollection = YES;
                    NSLog(@"1111111111111");
                    return;
                }else{
                    [_FMPlayerV.likeButton setBackgroundImage:[UIImage imageNamed:@"circlelist_heart@2x.png"] forState:UIControlStateNormal];//没收藏过不变红
                    _FMPlayerV.isCollection = NO;
                    NSLog(@"22222222222222");
                    
                }
            }
        }
            
    }
    
 
}



- (void)viewDidLoad {
    [super viewDidLoad];

 
   
    
    
    
    self.view.backgroundColor = [UIColor whiteColor];
    
    
    //       给导航栏上放自定义label
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 100 * WIDTH, 30 * HEIGHT)];
    [view setBackgroundColor:[UIColor clearColor]];
    self.navigationItem.titleView = view;
    _myTitle = [[UILabel alloc]initWithFrame:CGRectMake(WIDTH * (-375/2 + 100), 0, WIDTH * 300, HEIGHT * 30)];
    _myTitle.text = self.title;
    _myTitle.textAlignment = NSTextAlignmentCenter;//居中
    _myTitle.textColor = [UIColor whiteColor];
    [_myTitle setFont:[UIFont fontWithName:@"Helvetica-Bold" size:20]];//加粗字体
    [view addSubview:_myTitle];
    
    
    
    self.view.backgroundColor = [UIColor whiteColor];
    UIImage *image2 = [UIImage imageNamed:@"VList_Left@2x.png"];
    image2 = [image2 imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithImage:image2 style:UIBarButtonItemStylePlain target:self action:@selector(back)];
    

    
    
    //根据坐标取出对应的歌曲 链接
    
    FMPersonModel *model = [_Audio objectAtIndex:self.indexPath.row];
    //创建audioStreamer
    self.musicURL = model.playUrl32;
    _url = [NSURL URLWithString:model.playUrl32];
    _audioPlayer = [[STKAudioPlayer alloc]init];
    [_audioPlayer playURL:_url];//开始播放
    


    
    
    _FMPlayerV = [[FMPlayerView alloc]initWithFrame:self.view.bounds array:self.Audio];
    [self.view addSubview:_FMPlayerV];
    _FMPlayerV.myID  = self.trackId;
    _FMPlayerV.title = self.title;
    [_FMPlayerV release];

    
    
    _FMPlayerV.audioPlayer = _audioPlayer;
    _FMPlayerV.Audio = [NSMutableArray arrayWithArray:self.Audio];

    _FMPlayerV.myDelegate = self;

     _number = self.indexPath.row ;
    if(_FMPlayerV.isPlaying == YES && _FMPlayerV.isRotating == YES) {
        [_FMPlayerV.streamer  pause];//上一曲暂停
    }
    
    
    
     [self getMassage];
    
   

    
    
}


#pragma mark ---- 后台运行显示标题图片
- (void)playButtonPress:(UIImage *)image {
    

    
    Class playingInfoCenter = NSClassFromString(@"MPNowPlayingInfoCenter");
    
    if (playingInfoCenter) {
        
      
        NSMutableDictionary *songInfo = [ [NSMutableDictionary alloc] init];
        MPMediaItemArtwork *albumArt = [ [MPMediaItemArtwork alloc] initWithImage:image ];
        NSLog(@"title = %@",_myTitle.text);
        songInfo[MPMediaItemPropertyPlaybackDuration] = @(self.audioPlayer.duration);
        [ songInfo setObject:_myTitle.text forKey:MPMediaItemPropertyTitle ];
        [ songInfo setObject: albumArt forKey:MPMediaItemPropertyArtwork ];
        [ [MPNowPlayingInfoCenter defaultCenter] setNowPlayingInfo:songInfo ];
        
        
        
    }
    
    
}




-(void)background:(UIImage *)image
{
    [self playButtonPress:image];
}




-(void)getMassage
{
    
    
    
    
    NSString *string =[NSString stringWithFormat:@"http://mobile.ximalaya.com/mobile/track/detail?device=iPhone&trackId=%@",self.trackId];
    
    AFNetworkReachabilityManager *netWorkManager = [AFNetworkReachabilityManager sharedManager];
    
    
    AFHTTPRequestOperationManager* manager = [AFHTTPRequestOperationManager manager];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/plain",@"text/json",@"application/json",@"text/javascript",@"text/html",nil];
    [manager GET:string parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        [netWorkManager stopMonitoring];
        //  NSLog(@"使用AFN进行get请求 ===  %@",responseObject);
        NSMutableDictionary *dic = responseObject;
        FMPlayerModel *model = [[FMPlayerModel alloc]init];
        model.images = [NSMutableArray array];
        model.images = [NSMutableArray arrayWithArray:[dic objectForKey:@"images"]];
        model.richIntro = [dic objectForKey:@"richIntro"];
        model.playUrl64 = [dic objectForKey:@"playUrl64"];
        model.lyric = [dic objectForKey:@"lyric"];
        model.tags = [dic objectForKey:@"tags"];
        self.FMPlayerV.model = model;
        [model release];
    
  
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        
        NSLog(@"失败==== %@",error);
        
    }];
}


#pragma mark -- 跳到下一首
-(void)NextMusic
{
    if ([DataHandle shareHandleController].monitorNetwork == NO) {
        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"提示" message:@"您的网络不给力呀" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alert show];
        return;
    }

    _number ++;
//
    if (_number >= self.Audio.count ) {
        UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:@"提示" message:@"您已经是最后一首啦" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
        [alertView show];
        _number --;
        NSLog(@"最后一首啦");
        return;
    }

    
    if(_FMPlayerV.isPlaying == YES && _FMPlayerV.isRotating == YES) {
        [_FMPlayerV.audioPlayer pause];//暂停
    }
    
    FMPersonModel *model = [_Audio objectAtIndex:_number];
    //创建audioStreamer
    _url = [NSURL URLWithString:model.playUrl32];
     [_audioPlayer playURL:_url];//开始播放
   _FMPlayerV.audioPlayer = self.audioPlayer;//音频
    _myTitle.text = model.title;
    self.trackId = model.trackId;
    [self CollectionOrNo];//判断是否收藏过
    [self getMassage];
    
    [_FMPlayerV.button setBackgroundImage:[UIImage imageNamed:@"toolbar_pause_n@2x.png"] forState:UIControlStateNormal];//播放按钮图片
    [_FMPlayerV  Recovery];//图片复位
    [_FMPlayerV ContinueToRotate];//继续旋转
    [_FMPlayerV spinOn];

    
    _FMPlayerV.isPlaying = YES;
    _FMPlayerV.isRotating = YES;
    
    

}




#pragma mark -- 跳到上一首
-(void)lastSong
{
    
    if ([DataHandle shareHandleController].monitorNetwork == NO) {
        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"提示" message:@"您的网络不给力呀" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alert show];
        return;
    }
    
    if (_number == 0) {
        UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:@"提示" message:@"您已经是第一首啦" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
        [alertView show];
        NSLog(@"第一首啦");
        return;
    }
    
    _number --;
    if(_FMPlayerV.isPlaying == YES && _FMPlayerV.isRotating == YES) {
        [_FMPlayerV.audioPlayer pause];//暂停
    }
    
    FMPersonModel *model = [_Audio objectAtIndex:_number];
    //创建audioStreamer
    NSLog(@"model = %@",model.title);
    _url = [NSURL URLWithString:model.playUrl32];
    [_audioPlayer playURL:_url];//开始播放
    _FMPlayerV.audioPlayer = self.audioPlayer;//音频
    _myTitle.text = model.title;
    [self CollectionOrNo];//判断是否收藏过
    self.trackId = model.trackId;
    [self getMassage];
    
    [_FMPlayerV.button setBackgroundImage:[UIImage imageNamed:@"toolbar_pause_n@2x.png"] forState:UIControlStateNormal];//播放按钮图片
    [_FMPlayerV  Recovery];//图片复位
    [_FMPlayerV ContinueToRotate];//继续旋转
    [_FMPlayerV spinOn];
    
    
    
    
    _FMPlayerV.isPlaying = YES;
    _FMPlayerV.isRotating = YES;
    
    
}





#pragma mark ---- 判断是否收藏过
-(void)CollectionOrNo
{
    if ([DataHandle shareHandleController].monitorNetwork == NO) {
        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"提示" message:@"您的网络不给力呀" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alert show];
        return;
    }
    
    [[DataHandle shareHandleController]openDB];
    NSMutableArray *array = [[DataHandle shareHandleController]selectMusicFMCollection];
    if (array.count == 0) {
        [_FMPlayerV.likeButton setBackgroundImage:[UIImage imageNamed:@"circlelist_heart@2x.png"] forState:UIControlStateNormal];
        _FMPlayerV.isCollection = NO;
    }else{
        for (FMPersonModel *player in array) {
            
            
            if ([player.title isEqualToString:_myTitle.text]) {
                [_FMPlayerV.likeButton setBackgroundImage:[UIImage imageNamed:@"circlelist_heartup@2x.png"] forState:UIControlStateNormal];//收藏过变成红心
               // NSLog(@"111111");
                _FMPlayerV.isCollection = YES;
                return;
            }else{
                [_FMPlayerV.likeButton setBackgroundImage:[UIImage imageNamed:@"circlelist_heart@2x.png"] forState:UIControlStateNormal];//没收藏过不变红
               // NSLog(@"走肾");
                _FMPlayerV.isCollection = NO;
                
            }
        }
    }
    

    
}



#pragma mark --- 收藏
-(void)collection:(BOOL)result
{
    
    
    
    
   // NSLog(@"%ld",_number);
    
    FMPersonModel *model = [_Audio objectAtIndex:_number];
  //  NSLog(@"model.trackid = %@",model.trackId);
    [[DataHandle shareHandleController]openDB];
    NSMutableArray *array =  [[DataHandle shareHandleController]selectMusicFMCollection];
    for (FMPersonModel *personModel in array) {
       // NSLog(@"personModel.title  = %@",personModel.title );
   
        if ([personModel.title isEqualToString:model.title]) {
            //NSLog(@"llll?");
            return;
        }
    }
    [[DataHandle shareHandleController]insertMusicFMCollection:model];
 
    self.isCollection = YES;
   // NSLog(@"收藏");
    
    
}



-(void)drop:(BOOL)result
{
    [[DataHandle shareHandleController]openDB];
    FMPersonModel *model = [_Audio objectAtIndex:_number];

    [[DataHandle shareHandleController]deleteMusicFMCollection:model.title];

    self.isCollection = NO;
}








-(void)back
{
    [self.navigationController popViewControllerAnimated:YES];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
